﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASP;
using Infrastructure.Coding;
using Infrastructure.HardCoding;
using LinQProject;
using ServiceProject;
using ServiceProject.EntityService;
using ServiceProject.VirtualClasses;


public partial class Order : Page
{
    protected int OrderTypeProp
    {
        get
        {
            int result;
            if (Int32.TryParse(hdnOrderTypeProp.Value, out result))
                return result;
            return -1;
        }
        set { hdnOrderTypeProp.Value = value.ToString(); }
    }
    
    protected UserService userService=new UserService(database);
    protected ClientService clientService=new ClientService(database);
    protected OrderBussiness ordBussiness=new OrderBussiness(new OrderService(database), 
                                                                new OrderDetailService(database),
                                                               new ProductService(database)); 
    protected ProductBussiness prodBussiness=new ProductBussiness(new ProductService(database));
    protected InvoiceService invoiceService=new InvoiceService(database);
    protected ProviderService provideService=new ProviderService(database);
    protected MailManagement mailManage=new MailManagement();
    protected HtmlRender htmlRend = new HtmlRender();
   // protected MaintananceBussiness maintananceB=new MaintananceBussiness(database);

    private static readonly FarmacieDataClassesDataContext database = new FarmacieDataClassesDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString["orderType"] != null)
            {
                if (Request.QueryString["orderType"] == ((int)Enums.orderType.order).ToString())
                {
                    OrderTypeProp = (int) Enums.orderType.order;
                    lblucSel.Text = "Cos de cumparaturi";
                }
                else if (Request.QueryString["orderType"] == ((int)Enums.orderType.request).ToString())
                {
                    OrderTypeProp = (int) Enums.orderType.request;
                    lblucSel.Text = "Cerere de oferta";
                }
                else
                    return;
            }
            else
                return;

            LoadSelection();
        }

        //ucSel.Select += ucSel_Select;
        ucSel.Delete += ucSel_Delete;
        //ucProduct.Save += ucProduct_Save;
    }

    private void ucSel_Delete(object sender, ProductSelectEventArgs e)
    {
        bool isCos = (OrderTypeProp == (int)Enums.orderType.order);
        IDictionary<string, SelectedProduct> SelSelection = GetSelSelection(isCos);
        string keyToFind = string.Format("{0}", e.ProductId);
        SelSelection.Remove(keyToFind);
        if (SelSelection.Keys.Count == 0)
            Response.Redirect("~/Products.aspx");
        else
        {
            RefreshSelection(isCos, SelSelection);
            ucSel.LoadRepeater();
        }
    }

    //private void ucProduct_Save(object sender, EventArgs e)
    //{
    //    LoadSelection();
    //}

    //void ucSel_Select(object sender, ProductSelectEventArgs e)
    //{
    //    ucProduct.ProductId = e.ProductId;
    //    ucProduct.IsForModify = true;
    //    ucProduct.IsCos = OrderTypeProp == (int)Enums.orderType.order;

    //    ucProduct.LoadObjects();
    //    ucProduct.Visible = true;

    //    DropDownList ddl = (DropDownList)ucProduct.FindControl("ddlMaterial");
    //    if (ddl != null)
    //    {
    //        ddl.SelectedValue = e.MaterialId.ToString();
    //        ddl.Enabled = false;
    //    }

    //    DropDownList ddlC = (DropDownList)ucProduct.FindControl("ddlColour");
    //    if (ddlC != null && e.MaterialColourId != 0)
    //    {
    //        ddlC.SelectedValue = e.MaterialColourId.ToString();
    //        //ucProduct.SetImageColour(e.MaterialColourId);
    //        ddlC.Enabled = false;

    //    }

    //    TextBox txtPrice = (TextBox)ucProduct.FindControl("txtPrice");
    //    if (txtPrice != null)
    //        txtPrice.Text = e.ProductPrice.ToString();

    //    TextBox txtCant = (TextBox)ucProduct.FindControl("txtCant");
    //    if (txtCant != null)
    //        txtCant.Text = e.ProductQuantity.ToString();

    //    lblProd.Visible = true;
    //}

    private void LoadSelection()
    {
        bool isCos = (OrderTypeProp == (int) Enums.orderType.order);
        IDictionary<string, SelectedProduct> SelSelection = GetSelSelection(isCos);

        ucSel.IsCos = isCos;
        ucSel.Selection = SelSelection;
        ucSel.LoadRepeater();

        RefreshSelection(isCos, SelSelection);
    }

    private void RefreshSelection(bool isCos, IDictionary<string, SelectedProduct> SelSelection)
    {
        Control selCos = isCos ? Page.Master.FindControl("selCos") : Page.Master.FindControl("selCerere");
        controls_ucselection_ascx ucSelCos = selCos as controls_ucselection_ascx;
        if (ucSelCos != null)
        {
            ucSelCos.Selection = SelSelection;
            ucSelCos.LoadRepeater();
        }
    }

    private IDictionary<string, SelectedProduct> GetSelSelection(bool isCos)
    {
        return isCos ? (IDictionary<string, SelectedProduct>) Session["SelectionForCos"]
                   : (IDictionary<string, SelectedProduct>) Session["SelectionForRequest"];
    }

    protected void btnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("Products.aspx");
    }

    protected void btnFinalize_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(Session["username"].ToString()))
        {
            string destinationUrl = String.Format("~/VerifyRegister.aspx?orderType={0}", OrderTypeProp);
            Response.Redirect(destinationUrl);
        }
        else
        {
            //bussiness inserare comanda in Bd si trimitere mail cu proforma
            LinQProject.Order newOrder = SetNewOrder();
            if (newOrder == null)
                return;
            
            decimal totalCost = 0;
            bool isCos = (OrderTypeProp == (int)Enums.orderType.order);
            IDictionary<string, SelectedProduct> OrderSelection = GetSelSelection(isCos);
            IList<OrderDetail> orderDetailList =GetTotalCostAndOrderDetail(OrderSelection, ref totalCost);
            newOrder.TotalCost = totalCost;
            
            //save order and orderDetail
            ordBussiness.SaveOrder(newOrder,orderDetailList);
            
            // setting null for Session
            if (isCos)
                Session["SelectionForCos"] = null;
            else
                Session["SelectionForRequest"] = null;
            LoadSelection();
            
            //process for send Invoice/Request
            string mailTo = newOrder.Client.ClientEmail;
            string subject ;
            string bodyText;

            Provider myComp = provideService.GetProviderById((int)Enums.provider.myComp);
            IList<OrderDetail> listOrderDetail = ordBussiness.GetOrderDetailsForOrder(newOrder.OrderId);
            if (isCos)
            {
                Invoice newInvoice = new Invoice
                                         {
                                             InvoiceStatusId = ((int) Enums.invoiceStatus.send),
                                             InvoiceTotal = totalCost,
                                             isActive = true,
                                          OrderId = newOrder.OrderId
                                         };
                invoiceService.InsertInvoice(newInvoice);
                // send mail
                string percent = "100";
                //maintananceB.GetSetting((int) Enums.settings.invoicePercent).SetariValue;
                bodyText = htmlRend.GetTextForInvoice(newOrder, newInvoice, myComp, listOrderDetail, percent);
                subject = "scaune-ieftine.ro - Factura proforma Nr." + newInvoice.InvoiceId;

                mailManage.SendMail(bodyText, mailTo, subject);
            }
            else
            {
                subject = "scaune-ieftine.ro - Cererea de oferta Nr."+newOrder.OrderId;
                bodyText = string.Empty;
                    //htmlRend.GetTextForRequest(newOrder, myComp, listOrderDetail);
                mailManage.SendMail(bodyText,mailTo,subject);
            }
            //redirect for new order
            const string myFunctionOut = "clickerOut()";
            ScriptManager.RegisterStartupScript(this, GetType(), "clickOut", myFunctionOut, true);
            Response.Redirect("~/FinalizeOrder.aspx");
        }
    }

    private LinQProject.Order SetNewOrder()
    {
        LinQProject.Order newOrder = new LinQProject.Order();

        User userToFind = userService.GetUserByUserName(Session["username"].ToString());
        if (userToFind == null)
            return null;
        Client client = clientService.GetClientByUser(userToFind,null);
        if (client == null)
            return null;

        //new Order
        newOrder.ClientId           = client.ClientId;
        newOrder.IsActive           = true;
        newOrder.OrderLaunchedDate  = DateTime.Now;
        newOrder.OrderStatusId      = (int)Enums.orderStatus.launched;
        newOrder.OrderTypeId        = OrderTypeProp;
        newOrder.RecordStamp        = DateTime.Now;
        newOrder.UserId             = userToFind.UserId;

        return newOrder;
    }

    private IList<OrderDetail> GetTotalCostAndOrderDetail(IEnumerable<KeyValuePair<string, SelectedProduct>> OrderSelection, ref decimal totalCost)
    {
        IList<OrderDetail> orderDetailList = new List<OrderDetail>();
        foreach (var key in OrderSelection)
        {
            totalCost += key.Value.ProductPrice * key.Value.ProductQuantity;
            //var matColour = (int) key.Value.MaterialColourId == 0 ? null : key.Value.MaterialColourId;

            OrderDetail ord=new OrderDetail
                                {
                                    ProductCount = key.Value.ProductQuantity,
                                    //MaterialColourId = matColour,
                                    //ProductDetailId =
                                    //    prodBussiness.GetProductDetailByMaterial(key.Value.ProductId,
                                    //                                             key.Value.MaterialId).ProductDetailId,
                                    ProductUnitPrice = key.Value.ProductPrice,
                                    ProductTotalPrice = (key.Value.ProductPrice*key.Value.ProductQuantity)
                                };
            orderDetailList.Add(ord);
        }
        return orderDetailList;         
    }
}
